<?php
namespace common\models\wechat;

use common\models\wechat\WechatReplyKeyword;
use common\models\wechat\WechatReplyRule;
use yii\db\ActiveQuery;

class WechatReplyKeywordQuery extends ActiveQuery
{
    /**
     * 文本类型关键字过滤
     * @param $keyword
     * @return $this
     */
    public function keyword($keyword)
    {
        $this->andWhere([
            'or',
            ['and', '{{type}}=:typeMatch', '{{content}}=:keyword'], // 直接匹配关键字
            ['and', '{{type}}=:typeInclude', 'INSTR(:keyword, {{content}})>0'], // 包含关键字
//            ['and', '{{type}}=:typeInclude', ['like','content',$keyword]], // 包含关键字
            ['and', '{{type}}=:typeRegular', ':keyword REGEXP {{content}}'], // 正则匹配关键字
        ])
            ->addParams([
                ':keyword' => $keyword,
                ':typeMatch' => WechatReplyKeyword::TYPE_MATCH,
                ':typeInclude' => WechatReplyKeyword::TYPE_INCLUDE,
                ':typeRegular' => WechatReplyKeyword::TYPE_REGULAR
            ]);
        return $this;
    }

    /**
     * 查询公众号规则
     * @return $this
     */
    public function wechatRule($wid, $status = WechatReplyRule::STATUS_ACTIVE)
    {
        $this->joinWith([
            'rule' => function($query) use ($wid, $status) {
                if ($status !== null) {
//                    $query->active($status);
                }
                $query->andWhere(['wechat_reply_rule.wid' => $wid,'wechat_reply_rule.status'=>$status]);
            }
        ]);
        return $this;
    }



    /**
     * 过滤有效时间
     * @param $time
     * @return $this
     */
    public function limitTime($time)
    {
        $this->andWhere([
            'and',
            ['or', 'start_at<:time', 'start_at=0'],
            ['or', 'end_at>:time', 'end_at=0']
        ])
            ->addParams([
                ':time' => $time
            ]);
        return $this;
    }
}